<template>
  <div class="menuManage zy-content ">
    <Card title="" class="detail-content-layout">
      <Tree :data="data5" ref="tree" :render="renderContent"></Tree>
    </Card>
    <Modal :mask-closable="false"
           v-model="create"
           :title="addtitle"
           class="modal-content-layout"
           :loading="loading">
      <Form class="formList" ref="form" :model="formItem" :rules="ruleValidate" label-position="top">
        <div v-if="!formItem.id">
          <FormItem :label="$t('类别')" prop="type">
            <Select v-model="formItem.type" filterable :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item,index) in typeArr" :value="item.id" :key="index">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </div>
        <FormItem prop="icon" :label="formItem.type===2?$t('按钮Code'):$t('菜单图标')">
          <Input type="text" v-model="formItem.icon" :placeholder="`${$t('common.inputInfo')}`"
                 :maxlength="100"></Input>
        </FormItem>
        <FormItem label="URL" prop="url">
          <Input type="text" v-model="formItem.url" :placeholder="`${$t('common.inputInfo')}`" :maxlength="100"></Input>
        </FormItem>
        <div v-if="!formItem.id&&formItem.type===1">
          <FormItem :label="$t('菜单类型')" prop="menuType">
            <Select v-model="formItem.menuType" clearable filterable :placeholder="`${$t('common.inputInfo')}`"
                    disabled>
              <Option v-for="(item,index) in menuTypeArr" :value="item.id" :key="index">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </div>

        <FormItem prop="name" :label="formItem.type===2?$t('按钮名称'):$t('菜单名称')">
          <Input type="text" v-model="formItem.name" :placeholder="`${$t('common.inputInfo')}`"
                 :maxlength="100"></Input>
        </FormItem>
        <div v-if="formItem.type===1">
          <FormItem :label="$t('英文菜单')">
            <Input type="text" v-model="formItem.enName" :placeholder="`${$t('common.inputInfo')}`"
                   :maxlength="32"></Input>
          </FormItem>
        </div>

        <!-- <FormItem v-if="formItem.type===1" label="繁体菜单"  >
            <Input type="text" v-model="formItem.twName" placeholder="请输入菜单名称"  :maxlength="32"></Input>
        </FormItem> -->
        <div v-if="formItem.parentId&&formItem.type==1&&formItem.level!=1">
          <FormItem :label="$t('父级')" prop="parentId">
            <Select v-model="formItem.parentId" clearable :placeholder="`${$t('common.selectInfo')}`"
                    :disabled="!formItem.id">
              <Option v-for="(item,index) in parentIdArr" :value="item.id" :key="index">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </div>
        <!-- <div v-if="formItem.parentId&&formItem.type===1&&formItem.level!=1&&!formItem.id">
            <FormItem :label="$t('父级')">
                <Input type="text" v-model="formItem.parentName" :placeholder="`${$t('common.inputInfo')}`" disabled></Input>
            </FormItem>
        </div> -->

        <FormItem :label="$t('排序')" prop="sort">
          <Input type="text" v-model="formItem.sort" :placeholder="`${$t('common.inputInfo')}`"
                 :maxlength="100"></Input>
        </FormItem>
        <div v-if="formItem.type===1">
          <FormItem :label="$t('状态')" prop="status">
            <RadioGroup v-model="formItem.status">
              <Radio label="0">{{ $t('common.disable') }}</Radio>
              <Radio label="1">{{ $t('启用') }}</Radio>
            </RadioGroup>
          </FormItem>
        </div>


      </Form>
      <div slot="footer">
        <Button type="default" @click="create = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loading" @click="append(formItem.id,'form')">
          {{ $t('maintenance.Confirmed') }}
        </Button>
      </div>
    </Modal>
    <Modal :mask-closable="false"
           v-model="delShowF"
           class="modal-title-layout"
           :title="$t('common.Delete')">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delShowF = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="loading" @click="remove">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: "menuManage",
  data() {
    return {
      parentIdArr: [],
      menuTypeArr: [
        {id: 1, name: "PC"},
        {id: 2, name: "PAD"}
      ],
      typeArr: [
        {id: 1, name: this.$t('菜单')},
        {id: 2, name: this.$t('按钮')}
      ],
      delShowF: false,
      create: false,
      addtitle: "",
      loading: false,
      formItem: {},
      addData: {},
      removeData: {},
      data5: [
        {
          title: 'PC',
          expand: true,
          render: (h, {root, node, data}) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%',
                fontSize: '18px'
              }
            }, [

              h('span', [
                h('span', data.title)
              ]),
              h('span', [
                h('Button', {
                  props: Object.assign({}, this.buttonProps, {
                    icon: 'ios-add'
                  }),
                  style: {
                    marginLeft: '8px',
                    marginRight: '8px'
                  },
                  on: {
                    click: () => {
                      this.addClick(root, node, data, 0, 1, 1)
                    }
                  }
                }),
              ])
            ]);
          },
          children: []
        }, {
          title: 'PDA',
          expand: true,
          render: (h, {root, node, data}) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%',
                fontSize: '18px'
              }
            }, [

              h('span', [
                h('span', data.title)
              ]),
              h('span', [
                h('Button', {
                  props: Object.assign({}, this.buttonProps, {
                    icon: 'ios-add'
                  }),
                  style: {
                    marginLeft: '8px',
                    marginRight: '8px'
                  },
                  on: {
                    click: () => {
                      this.addClick(root, node, data, 0, 1, 2)
                    }
                  }
                }),
              ])
            ]);
          },
          children: []
        }
      ],
      buttonProps: {
        type: 'default',
        size: 'small',
      },
      expandIds: [],
      ruleValidate: {
        // type: [
        //     { required: true, message: this.$t('common.inputInfo'), trigger: 'change', }
        // ],
        // menuType: [
        //     { required: true, message: this.$t('common.inputInfo'), trigger: 'change', }
        // ],
        icon: [
          {required: true, message: this.$t('common.inputInfo'), trigger: 'blur',}
        ],
        url: [
          {required: true, message: this.$t('common.inputInfo'), trigger: 'blur',}
        ],
        name: [
          {required: true, message: this.$t('common.inputInfo'), trigger: 'blur',}
        ],
        parentId: [
          {required: true, type: 'number', message: this.$t('common.inputInfo'), trigger: 'change',}
        ],
        sort: [
          {required: true, message: this.$t('common.inputInfo'), trigger: 'blur',}
        ],
        status: [
          {required: true, message: this.$t('common.inputInfo'), trigger: 'change',}
        ],
      },
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getExpandId() {
      const nodes = this.$refs.tree.$data.flatState;
      let ids = [];
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].node.expand && nodes[i].node.id) {
          ids.push(nodes[i].node.id)
        }
      }
      this.expandIds = ids
    },
    setExpand(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (this.expandIds.includes(arr[i].id)) {
          arr[i].expand = true
        }
        if (arr[i].children) {
          this.setExpand(arr[i].children)
        }
      }
    },
    getList() {
      this.axios({
        method: 'get',
        url: "/basic/menu/list",
        params: {}
      }).then(res => {
        if (res.code === 200) {
          const data1 = res.data[0];
          const data2 = res.data[1];

          this.setExpand(data1)
          this.setExpand(data2)

          this.data5[0].children = data1
          this.data5[1].children = data2
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    renderContent(h, {root, node, data}) {
      if (!data) return h('span', '数据加载中...'); // 防止 data 为 undefined

      if (data.type == 2) {
        if (data.status == 0) {
          return h('span', {
            style: {
              display: 'inline-block',
              width: '100%',
              fontSize: '15px',
              color: "#A9A9A9",
            },
          }, [
            h('span', [
              h('span', data.name),
            ]),
            h('span', {
              style: {
                display: 'inline-block',
                float: 'right',
                marginRight: '32px',
              },
            }, [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-remove',
                }),
                style: {
                  marginLeft: '8px',
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.removeClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                }),
                on: {
                  click: () => {
                    this.addClick(root, node, data, 1)
                  },
                },
              }),
            ]),
          ]);
        } else {
          return h('span', {
            style: {
              display: 'inline-block',
              width: '100%',
              fontSize: '15px',
            },
          }, [
            h('span', [
              h('span', data.name),
            ]),
            h('span', {
              style: {
                display: 'inline-block',
                float: 'right',
                marginRight: '32px',
              },
            }, [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-remove',
                }),
                style: {
                  marginLeft: '8px',
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.removeClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                }),
                on: {
                  click: () => {
                    this.addClick(root, node, data, 1)
                  },
                },
              }),
            ]),
          ]);
        }
      } else {
        if (data.status == 0) {
          return h('span', {
            style: {
              display: 'inline-block',
              width: '100%',
              fontSize: '15px',
              color: '#A9A9A9',
            },
          }, [
            h('span', [
              h('span', data.name),
            ]),
            h('span', {
              style: {
                display: 'inline-block',
                float: 'right',
                marginRight: '32px',
              },
            }, [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-add',
                }),
                style: {
                  marginLeft: '8px',
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.addClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-remove',
                }),
                style: {
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.removeClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                }),
                on: {
                  click: () => {
                    this.addClick(root, node, data, 1)
                  },
                },
              }),
            ]),
          ]);
        } else {
          return h('span', {
            style: {
              display: 'inline-block',
              width: '100%',
              fontSize: '15px',
            },
          }, [
            h('span', [
              h('span', data.name),
            ]),
            h('span', {
              style: {
                display: 'inline-block',
                float: 'right',
                marginRight: '32px',
              },
            }, [
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-add',
                }),
                style: {
                  marginLeft: '8px',
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.addClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-remove',
                }),
                style: {
                  marginRight: '8px',
                },
                on: {
                  click: () => {
                    this.removeClick(root, node, data)
                  },
                },
              }),
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-create-outline',
                }),
                on: {
                  click: () => {
                    this.addClick(root, node, data, 1)
                  },
                },
              }),
            ]),
          ]);
        }
      }
    },
    addClick(root, node, data, type, level, menutype) {
      console.log(data, type, 'level')
      this.addData = data
      this.$refs.form.resetFields();
      if (type === 1) {
        this.addtitle = `${this.$t('common.Edit')}`;
        this.formItem = {
          id: data.id,
          level: data.level,
          menuType: data.menuType,
          name: data.name,
          // parentId: data.parentId, // 先不直接赋值，等请求成功后再赋值
          sort: data.sort.toString(),
          type: data.type,
          url: data.url,
          enName: data.enName,
        };

        if (data.type === 2) {
          this.formItem.icon = data.code;
          this.formItem.parentId = data.parentId; // 按钮类型直接赋值 parentId
          this.create = true;
        } else {
          this.formItem.status = data.status.toString();
          this.formItem.icon = data.icon;

          if (data.level != 1) {
            this.axios({
              method: 'get',
              url: "/basic/menu/getMenuByLevelAndType",
              params: {
                level: data.level - 1,
                menuType: data.menuType,
              },
            }).then((res) => {
              if (res.code === 200) {
                this.parentIdArr = res.data;
                this.formItem.parentId = data.parentId; // 请求成功后再赋值 parentId
                this.create = true;
              } else {
                this.$Message.warning({content: res.msg, duration: 6, closable: true});
                this.parentIdArr = []; // 请求失败时赋值空数组，避免 undefined
                this.create = true; // 仍然打开模态框，但可能无法选择父级
              }
            }).catch(() => {
              this.parentIdArr = []; // 请求异常时赋值空数组
              this.create = true; // 仍然打开模态框，但可能无法选择父级
            });
          } else {
            this.formItem.parentId = data.parentId;
            this.create = true;
          }
        }
      } else {
        this.addtitle = `${this.$t('common.New')}`;
        this.formItem = {
          parentName: data.name,
          url: '/tpm/',
          status: "1",
          type: 1,
          level: data.level + 1
        };

        if (data.menuType) {
          this.formItem.menuType = data.menuType;
        } else {
          this.formItem.menuType = menutype;
        }

        // if (level === 1) {
        //   data.level = 0;
        // }

        this.axios({
          method: 'get',
          url: "/basic/menu/getMenuByLevelAndType",
          params: {
            level: data.level,
            menuType: data.menuType || 0,
          },
        }).then((res) => {
          console.log(res, 'getMenuByLevelAndType')
          if (res.code === 200) {
            this.parentIdArr = res.data;
            this.formItem.parentId = data.id;
            this.create = true;
          } else {
            this.$Message.warning({content: res.msg, duration: 6, closable: true});
            this.parentIdArr = []; // 请求失败时赋值空数组
            this.create = true; // 仍然打开模态框，但可能无法选择父级
          }
        }).catch(() => {
          this.parentIdArr = []; // 请求异常时赋值空数组
          this.create = true; // 仍然打开模态框，但可能无法选择父级
        });
        console.log(this.formItem, 'this.formItemthis.formItem')
      }
    },
    append(id, name) {
      this.$refs[name].validate((valid) => {
        if (!valid) {
          console.log('验证失败字段:', this.$refs[name].fieldsError); // 打印验证失败详情
        } else {
          this.loading = true;
          delete this.formItem.parentName;

          this.getExpandId();

          if (id) {
            console.log(id, 'id')
            // 确保 formItem.parentId 是数字或字符串，避免 undefined
            if (this.formItem.parentId === undefined || this.formItem.parentId === null) {
              this.formItem.parentId = 0; // 默认值
            }

            this.axios({
              method: 'post',
              url: "/basic/menu/update",
              data: this.formItem,
            }).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.$Message.success(res.data);
                this.getList();
                this.create = false;
              } else {
                this.$Message.warning({content: res.msg, duration: 6, closable: true});
              }
            });
          } else {
            console.log('noid')
            let data = this.addData;
            console.log(data, 'data')
            // this.formItem.level = Number(data.level) + 1;

            if (this.formItem.type === 2) {
              this.formItem.parentId = data.id.toString();
            }

            // 确保 formItem.parentId 是数字或字符串，避免 undefined
            if (this.formItem.parentId === undefined || this.formItem.parentId === null) {
              this.formItem.parentId = 0; // 默认值
            }

            this.axios({
              method: 'post',
              url: "/basic/menu/newAdd",
              data: this.formItem,
            }).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.$Message.success(res.data);
                this.getList();
                this.create = false;
              } else {
                this.$Message.warning({content: res.msg, duration: 6, closable: true});
              }
            });
          }
        }
      });
    },
    removeClick(root, node, data) {
      this.delShowF = true
      this.removeData.root = root
      this.removeData.node = node
      this.removeData.data = data
    },
    remove() {
      let root, node, data;
      root = this.removeData.root
      node = this.removeData.node
      data = this.removeData.data
      this.loading = true
      this.getExpandId()
      this.axios({
        method: 'post',
        url: "/basic/menu/delete",
        data: {
          deleteDto: [
            {
              types: data.type,
              code: data.code,
              id: data.id
            }
          ],
        }
      }).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.$Message.success(res.data)
          this.delShowF = false
          this.getList();
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.menuManage {
  font-size: 15px;


}
</style>

<style lang="scss">
.menuManage .ivu-btn {
  //color: #00142D;
  //border-color: #00142D;
  i {
    font-weight: bold;
    //color: #00142D;
  }

  &:hover {
    i {
      //color: #035beb !important;
      color: #FFFFFF !important;
    }

    border-color: #035beb;
    background: #035beb;
  }
}
</style>
